<template>
  <div style="width: 100%">
    <el-main class="drawerMain">
      <el-row
        v-for="(item, index) in afterArr"
        :key="index"
      >
        <el-col :span="24">
          <div class="comment">
            <div class="popover-box user-popover popover">
              <a class="user-link">
                <el-image
                  :src="item.avatar"
                  class="lazy avatar"
                />
              </a>
            </div>
            <div class="content-box">
              <div class="comment-main">
                <div class="content">
                  <el-card>
                    <div v-if="item.type === 0" v-html="item.text" />
                    <v-md-editor
                      v-else
                      v-model="item.text"
                      mode="preview"
                    />
                  </el-card>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-main>
    <el-input
      v-model="prompt"
      class="send"
      placeholder="发送消息给AI"
    >
      <el-button slot="append" @click="send">
        <svg-icon
          icon-class="ali-chat-send"
        />
      </el-button>
    </el-input>
  </div>
</template>
<script>
import { chat } from '@/api/chat'
export default {
  props: ['text'],
  data() {
    return {
      prompt: '',
      beforeArr: [],
      afterArr: []
    }
  },
  created() {
    this.prompt = this.text
    this.send()
  },
  methods: {
    send() {
      this.afterArr.push({
        type: 0,
        text: this.prompt,
        avatar: this.$store.state.user.avatar
      })
      this.afterArr.push({
        type: 1,
        text: `![](https://cdn.lesscoding.net/chatGPT_loading.gif)`,
        avatar: 'https://cdn.lesscoding.net/charge_duck.png'
      })
      const tempText = this.prompt
      this.prompt = ''
      chat({ prompt: tempText, beforeChats: this.afterArr}).then(resp => {
        const result = resp.data
        result.forEach(item => {
          item.avatar = item.type === 0 ? this.$store.state.user.avatar : 'https://cdn.lesscoding.net/charge_duck.png'
          item.text = item.text.replaceAll('\n\n', '<br/>')
          item.text = item.text.replaceAll('\n', '<br/>')
        })
        this.afterArr = result
        console.log(result, 'chatGPTResult')
        console.log(this.afterArr, 'afterArr')
      })
    }
  }
}
</script>
<style>
  @import "../../styles/comment.scss";
  .send{
    position:fixed;
    text-align:center;
    bottom:5px;
    margin:0 auto;
    width:400px;
    color: #5c6b77;
    z-index: 2004
  }
  .drawerMain{
    height: 80%;
    padding-bottom: 20px;
  }
</style>
